package com.xy.cloud.utils;

import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Arrays;

/**
 * 封装工具类
 * @author kuku_zhongzi
 */

public class WxDecryptUtil {

    public static boolean initialized = false;
    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";

    /**
     * 解密数据
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv) {
        String result = "";
        try {
            byte[] resultByte = decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if (null != resultByte && resultByte.length > 0) {
                result = new String(decode(resultByte));
                JSONObject jsonObject = JSONObject.fromObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if (!appId.equals(decryptAppid)) {
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param content 密文
     */
    public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) {
        initialize();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    public static void initialize() {
        if (initialized){
            return;
        }
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    // 生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }

    /**
     * 删除解密后明文的补位字符
     *
     * @param decrypted 解密后的明文
     * @return 删除补位字符后的明文
     */
    public static byte[] decode(byte[] decrypted) {
        int pad = decrypted[decrypted.length - 1];
        if (pad < 1 || pad > 32) {
            pad = 0;
        }
        return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
    }

    public static String getSignature2(String rawData, String sessionKey) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String stringASCII = rawData + sessionKey;
        String signature2 = null;
        try {
            //指定sha1算法
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(stringASCII.getBytes("UTF-8"));
            //获取字节数组
            byte messageDigest[] = digest.digest();
            // 创建 Hex 字符串
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
                signature2 = hexString.toString().toLowerCase();
            }
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw e;
        }
        return signature2;
    }


    public static void main(String[] args) {

            String appId = "wxd81b07accab29231";
            String encryptedData = "GrR+0KWZjRROAkDvTYoD8uLNioEtx0q/cPq43GkmcKk2udsO16GcCH2G063Xs7CDzr4aCzGoQvhQaGLcHo5WDxA+qp1g1d5khxVvRleYrPOyHXvglrvz/Mg4/SowL+XeGI3IB+JL+zGUyKGiaCWLzLHDtP9Bi6pLHpfeyap1qvKRl4p4BQ+ba/ivbe0Ien3znGxO4MfXm4rMIlV97YpKhNvvopLmrRHQg1ma28cUTce/jw3k30ZXfhM5zXSDR7YGVstFJDXzuzy99s8iwZuvAz16z0NAO/cFqRvhpkfZ5giyOnbVjMFYvhWp3nOYuGa4bYIscrWjaa9OornHTozdqjx+6JsXPzRfYEDOV/jMgakkKwdtLJx4d5hGg6rbXvJ9ljPpr4tzkSmb6+xUWrIPLA==";
            String sessionKey = "giiSQBQc5BKHtZBSgFKEEg==";
            String iv = "pVMoLtRB3UT8sCEE7BBhyw==";
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(WxDecryptUtil.decrypt(appId, encryptedData, sessionKey, iv));
        // jsonObject => {"phoneNumber": "13580006666","purePhoneNumber": "13580006666","countryCode": "86","watermark":{"appid":"APPID", "timestamp": 1618983}}
            System.out.println("用户绑定的手机号（国外手机号会有区号）：" + jsonObject.getString("phoneNumber"));  //  13580006666
            System.out.println("不带区号的手机号：" + jsonObject.getString("purePhoneNumber"));  // 13580006666
            System.out.println("区号：" + jsonObject.getString("countryCode"));  // 86
    }
}
